<?php

/**
* Get a web file (HTML, XHTML, XML, image, etc.) from a URL.  Return an
* array containing the HTTP server response header fields and content.
*/
function get_web_page( $url )
{
    $options = array(
    CURLOPT_RETURNTRANSFER => true,     // return web page
    CURLOPT_HEADER         => false,    // don't return headers
    CURLOPT_FOLLOWLOCATION => true,     // follow redirects
    CURLOPT_ENCODING       => "utf-8",       // handle all encodings
    CURLOPT_USERAGENT      => "spider", // who am i
    CURLOPT_AUTOREFERER    => true,     // set referer on redirect
    CURLOPT_CONNECTTIMEOUT => 120,      // timeout on connect
    CURLOPT_TIMEOUT        => 120,      // timeout on response
    CURLOPT_MAXREDIRS      => 10,       // stop after 10 redirects        
    );

    $ch      = curl_init( $url );
    curl_setopt_array( $ch, $options );
    $content = curl_exec( $ch );
    $err     = curl_errno( $ch );
    $errmsg  = curl_error( $ch );
    $header  = curl_getinfo( $ch );
    curl_close( $ch );

    $header['errno']   = $err;
    $header['errmsg']  = $errmsg;
    $header['content'] = $content;
    return $header;
}


/**
* Get FIRST childnode with tag name and class name
* 
* @param DOMElement $parentNode
* @param mixed $tagName
* @param mixed $className
* @return DOMNode
*/
function getNodebyTagNameAndClass($parentNode, $tagName, $className)
{
    //$parentNode = new DOMElement();
    $nodes = $parentNode->getElementsByTagName($tagName);
    for ($i = 0; $i < $nodes->length; $i++)
    {
        $node = $nodes->item($i);
        $currentClass = $node->getAttribute("class");
        if ($currentClass == $className)
        {
            return $node;
        }
    }
    return null;
}

/**
* Remove everything except numbers in a string
* 
* @param mixed $s
* @return int
*/
function getNumberOnly($s)
{
    $regex = '/[^0-9]/';
    $s = preg_replace($regex,'',$s);
    return (int)$s;
}

/**
* Get the string between two given signal
* 
* @param mixed $str
* @param mixed $start
* @param mixed $end
* @return string
*/
function getStrBetween($str, $start, $end)
{
    $posStart = stripos($str,$start);        
    $posEnd = stripos($str,$end);
    $len = $posEnd - $posStart;
    $posStart += strlen($start);
    return substr($str,$posStart,$len);
}

/**
* Add . every three digits
* 
* @param mixed $number
* @param mixed $fractional
* @return mixed
*/
function formatMoney($number, $fractional=false) {
    if ($fractional) {
        $number = sprintf('%.2f', $number);
    }
    while (true) {
        $replaced = preg_replace('/(-?\d+)(\d\d\d)/', '$1.$2', $number);
        if ($replaced != $number) {
            $number = $replaced;
        } else {
            break;
        }
    }
    return $number;
} 

/* End of file common.php */
/* Location: ./application/helpers/common.php */